package com.lcp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcp.entity.User;
import com.lcp.mapper.UserMapper;
import com.lcp.service.UserService;
import com.lcp.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public User findByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public User register(User user) {
        // 检查用户名是否已存在
        if (findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRole("USER");
        user.setStatus(String.valueOf(1));
        
        userMapper.insert(user);
        return user;
    }

    @Override
    public String login(User user) {
        try {
            // 先查询用户是否存在
            User dbUser = findByUsername(user.getUsername());
            if (dbUser == null) {
                throw new RuntimeException("用户名或密码错误");
            }

            // 使用AuthenticationManager进行认证
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())
            );
            
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return jwtUtil.generateToken(user.getUsername());
        } catch (Exception e) {
            throw new RuntimeException("用户名或密码错误");
        }
    }

    @Override
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = findByUsername(authentication.getName());
        if (user != null) {
            user.setPassword(null); // 清除密码，避免泄露
        }
        return user;
    }

    @Override
    public void updateUser(User user) {
        User currentUser = getCurrentUser();
        user.setId(currentUser.getId());
        user.setPassword(null); // 不允许通过此方法修改密码
        userMapper.updateById(user);
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {
        User currentUser = getCurrentUser();
        
        if (!passwordEncoder.matches(oldPassword, currentUser.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        currentUser.setPassword(passwordEncoder.encode(newPassword));
        userMapper.updateById(currentUser);
    }
} 